﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace TCPClientServer_Test
{
    //class Message
    //{
    //    public IPAddress Address;
    //    public int ID;
    //    public byte[] Bytes;
    //}

    static class HostThread
    {
        static List<ClientThread> listeningThreads;
        static TcpListener listener;
        static private System.Object lockObject;
        static int port = 13000;
        static IPAddress localAddr;
        static public bool keepListening;
        //static public Queue<Message> MessagesReceived;

        static HostThread()
        {
            listeningThreads = new List<ClientThread>();
            //MessagesReceived = new Queue<Message>();
            lockObject = new System.Object();
            localAddr = Dns.GetHostAddresses(Dns.GetHostName())
                    .First(a => a.AddressFamily == AddressFamily.InterNetwork);
            listener = new TcpListener(localAddr, port);
            keepListening = false;
        }

        static public void Listen()
        {
            listener.Start();
            keepListening = true;
            while (keepListening)
            {
                Console.Write("Waiting for a connection... ");
                TcpClient client = listener.AcceptTcpClient();
                Console.WriteLine("Client Connected!");
                ClientThread handler = new ClientThread(ref client);
                handler.ID = listeningThreads.Count;
                handler.StartListening();
                int[] array = new int[1];
                array[0] = handler.ID;
                handler.Send(NetworkManager.IntToBytes(array));
                listeningThreads.Add(handler);
            }
        }

        static public void Forward(Byte[] message, int SendingID)
        {
            lock (lockObject)
            {
                foreach (ClientThread c in listeningThreads)
                {
                    if (c.ID != SendingID)
                        c.Send(message);
                }
            }
        }
    }
}
